// AuthLayout.tsx 权限 + 页面布局
import {
  Navigate,
  Outlet,
  useLocation,
  useNavigate,
  useMatches,
} from "react-router-dom";
import { getToken } from "./utils/auth";
import {
  Layout,
  theme,
  Menu,
  Avatar,
  Dropdown,
  Popover,
  Tabs,
  Badge,
} from "antd";
import { ThemeController } from "@/components/ThemeController";
import { useState, useEffect, Suspense } from "react";
import type { MenuProps, TabsProps } from "antd";

import { useTranslation } from "react-i18next";
import {
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
  BellOutlined,
  FieldTimeOutlined,
  SnippetsOutlined,
} from "@ant-design/icons";

const { Header, Content, Sider, Footer } = Layout;

type MenuItem = Required<MenuProps>["items"][number];
function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

const tabLists: TabsProps["items"] = [
  {
    key: "notification",
    label: "通知",
    children: (
      <div>
        {[1, 2, 3, 4, 5].map((i) => (
          <div
            key={i}
            className="flex justify-between items-center not-last:mb-2"
          >
            <div className="flex items-center">
              <Avatar size={42} icon={<UserOutlined />} />
              <div className="ml-4 text-left">
                <div className="text-lg font-bold">用户名{i}</div>
                <div className="text-sm text-gray-500">职位{i}</div>
              </div>
            </div>
          </div>
        ))}
      </div>
    ),
  },
  {
    key: "private-message",
    label: "私信",
    children: (
      <div>
        {[1, 2, 3, 4, 5].map((i) => (
          <div
            key={i}
            className="flex justify-between items-center not-last:mb-2"
          >
            <div className="flex items-center">
              <div className="ml-4 text-left">
                <div className="text-md">私信{i}</div>
              </div>
            </div>
          </div>
        ))}
      </div>
    ),
  },
  {
    key: "to-do",
    label: "待办",
    children: "Content of Tab Pane 3",
  },
];
const onChange = (key: string) => {
  console.log(key);
};
const content = (
  <div className="w-70">
    <Tabs
      defaultActiveKey="1"
      centered
      tabBarGutter={50}
      items={tabLists}
      onChange={onChange}
    />
  </div>
);

export default function AuthLayout() {
  const navigate = useNavigate();
  const location = useLocation();
  const matches = useMatches();
  const isLoggedIn = !!getToken();
  // 定义退出登录的处理函数
  const handleLogout = () => {
    // 跳转至登录页面
    navigate("/login");
    // 清空 localStorage
    localStorage.clear();
  };
  const dropItems: MenuProps["items"] = [
    {
      key: "logout", // 退出
      label: <a onClick={handleLogout}>退出登陆</a>,
    },
    {
      key: "setting", // 退出
      label: <a>设置</a>,
    },
  ];

  // 获取当前路由的认证要求
  const needAuth = matches.some(
    (match) => (match.handle as { auth?: boolean })?.auth
  );
  const { t } = useTranslation();
  const items: MenuItem[] = [
    getItem(t("home"), "/home", <PieChartOutlined />),
    getItem(t("users"), "/users", <UserOutlined />, [
      getItem(t("user"), "/users/user"),
      getItem(t("setting"), "/users/setting"),
    ]),
    getItem(t("team"), "/sub", <TeamOutlined />, [
      getItem(t("calendar"), "/sub/calendar", <UserOutlined />),
      getItem(t("table"), "/sub/table", <SnippetsOutlined />),
      getItem(t("timeLine"), "/sub/timeLine", <FieldTimeOutlined />),
    ])
  ];
  if (needAuth && !isLoggedIn) {
    return (
      <Navigate
        to="/login"
        state={{
          from: location,
          requireAuth: true, // 标识需要认证
        }}
        replace
      />
    );
  }

  // 菜单状态管理
  const [collapsed, setCollapsed] = useState(false);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const { token } = theme.useToken();
  // console.log("token", token); // 可以获取所有的主题色，和一些常见配置
  // 根据路径初始化展开的菜单
  useEffect(() => {
    const defaultOpenKeys = items
      .filter((item) => (item as { children?: MenuItem[] }).children?.length)
      .map((parent) => parent!.key as string)
      .filter((parentKey) => location.pathname.startsWith(parentKey));
    setOpenKeys(() => {
      return [...openKeys, ...defaultOpenKeys];
    });
    console.log("defaultOpenKeys", defaultOpenKeys);
  }, [location]);

  // 处理菜单点击
  const handleMenuClick: MenuProps["onClick"] = (e) => {
    navigate(e.key);
  };

  // 处理子菜单展开
  const handleOpenChange: MenuProps["onOpenChange"] = (keys) => {
    setOpenKeys(keys);
  };

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider
        collapsible
        collapsed={collapsed}
        style={{
          background: token.colorBgContainer,
          borderRight: `1px solid ${token.colorBorderSecondary}`,
        }}
        onCollapse={(value) => setCollapsed(value)}
      >
        <div className="demo-logo-vertical" />
        <Menu
          selectedKeys={[location.pathname]}
          openKeys={openKeys}
          mode="inline"
          items={items}
          onClick={handleMenuClick}
          onOpenChange={handleOpenChange}
        />
      </Sider>
      <Layout>
        <Header
          style={{
            padding: 0,
            background: token.colorBgContainer,
            borderBottom: `1px solid ${token.colorBorderSecondary}`,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            paddingInline: token.paddingLG,
          }}
        >
          <div className="w-full flex justify-between">
            <div className="w-1/2 relative">
              {/* 新增动画层 */}
              <div className="theme-transition-layer"></div>
              <ThemeController />
            </div>
            <div className="w-1/2 flex justify-end mt-2">
              <div className="mr-6">
                <Popover placement="bottom" content={content} trigger={"click"}>
                  <Badge count={5}>
                    <BellOutlined
                      style={{
                        color: token.colorTextDescription,
                        fontSize: token.fontSizeHeading2,
                      }}
                    />
                  </Badge>
                </Popover>
              </div>

              <Dropdown
                menu={{ items: dropItems }}
                placement="bottom"
                arrow={{ pointAtCenter: true }}
              >
                <Avatar size={42} icon={<UserOutlined />} />
              </Dropdown>
              {/* 占位 */}
              <div className="w-16 border-2 border-gray-200 h-12 ml-4">
                占位
              </div>
            </div>
          </div>
        </Header>
        <Content
          style={{
            margin: "24px 16px 0",
            overflow: "auto",
            height: "calc(100vh - 200px)",
          }}
        >
          <div className="main-content">
            <Suspense fallback={<div>Loading...</div>}>
              <Outlet />
            </Suspense>
          </div>
        </Content>
        <Footer
          style={{
            textAlign: "center",
            background: token.colorBgContainer,
            height: token.controlHeightLG,
            lineHeight: token.controlHeightLG + "px",
            padding: 0,
          }}
        >
          Ant Design ©2023 Created by Ant UED
        </Footer>
      </Layout>
    </Layout>
  );
}
